package model

import (
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"shop-api/databases/mysql"
)

type Good struct {
	Base
	Name    string         `json:"name" gorm:"type:varchar(255);not null;comment:商品名称"`
	TypeID  int64          `json:"type_id" gorm:"index;not null;comment:商品类型ID"`
	Point   int64          `json:"point" gorm:"not null;comment:积分"`
	IsCheap bool           `json:"is_cheap" gorm:"not null;default:0;comment:是否是特价商品"`
	Image   datatypes.JSON `json:"image" gorm:"type:json;comment:商品图片"`
	Desc    string         `json:"desc" gorm:"type:text;comment:商品描述"`
}

func (Good) GetList(offset, limit, typeID uint, keyword string) ([]*Good, error) {
	var infos []*Good
	err := mysql.WithClient(func(db *gorm.DB) error {
		if typeID > 0 {
			db = db.Where("type_id = ?", typeID)
		}
		if keyword != "" {
			db = db.Where("name like ?", "%"+keyword+"%")
		}
		return db.Offset(int(offset)).Limit(int(limit)).Find(&infos).Error
	})
	if err != nil {
		return nil, err
	}
	return infos, nil
}

func (Good) GetListByIDs(goodIds []uint) ([]*Good, error) {
	var infos []*Good
	err := mysql.WithClient(func(db *gorm.DB) error {
		return db.Where("id in (?)", goodIds).Find(&infos).Error
	})
	if err != nil {
		return nil, err
	}
	return infos, nil
}
